//
//  KAContactView.swift
//  kano
//
//  Created by Sophia on 2024/8/22.
//

import UIKit
import RxCocoa
import RxSwift

enum contactIconType {
    case arrow
    case contact
    case clear
}

class KAContactView: UIView {
    
    private let disposeBag = DisposeBag()
    
    var editingHandle: ((_ content: String)->())? = nil
    
    var var_index: Int = 0

    lazy var var_type: contactIconType = .clear
    
    var lastTimeInterval: TimeInterval = 0
    var tfInfo = KATFInfo()
    
    lazy var var_bgView: UIView = {
        let var_bgView = UIView();
        var_bgView.layer.masksToBounds = true
        var_bgView.layer.cornerRadius = kscale(10);
        var_bgView.backgroundColor = .colorf2f2f5
//        var_bgView.frame = CGRectMake(kscale(20), 0, var_screenWidth-kscale(40), kscale(46))
        var_bgView.frame = bounds
        return var_bgView
    }()
    
    lazy var contentTF: UITextField = {
        let contentTF = UITextField()
        contentTF.font = UIFont.systemFont(ofSize: kscale(14.0))
        let var_placeholderString = NSMutableAttributedString.init(string: "", attributes: [.font : kFontSize(16), .foregroundColor : UIColor.black])
        contentTF.attributedPlaceholder = var_placeholderString;
        contentTF.textColor = .black
        contentTF.delegate = self;
        contentTF.returnKeyType = .default
        contentTF.keyboardType = .asciiCapable
        contentTF.isUserInteractionEnabled = var_type == .clear ? true : false
        return contentTF
    }()
    
    lazy var var_rightBtn: UIButton = {
        let var_rightBtn = UIButton()
        if var_type == .arrow {
            var_rightBtn.setImage(UIImage(named: "cell_arrow"), for: .normal)
            var_rightBtn.setImage(UIImage(named: "cell_arrow"), for: .selected)
        }
        else if var_type == .clear {
            var_rightBtn.setImage(UIImage(named: "text_clear"), for: .normal)
            var_rightBtn.setImage(UIImage(named: "text_clear"), for: .selected)
        }
        else {
            var_rightBtn.setImage(UIImage(named: "cell_contact"), for: .normal)
            var_rightBtn.setImage(UIImage(named: "cell_contact"), for: .selected)
        }
        var_rightBtn.isHidden = var_type == .clear ? true : false
//        var_rightBtn.isUserInteractionEnabled = var_type == .clear ? true : false
        return var_rightBtn
    }()
    
    static func ka_cell(for tableView: UITableView) -> KAApplyInfoCell {
        let var_identifityId = NSStringFromClass(self)
        var var_cell = tableView.dequeueReusableCell(withIdentifier: var_identifityId)
        if var_cell == nil {
            var_cell = KAApplyInfoCell.init(style: .default, reuseIdentifier: var_identifityId)
        }
        return var_cell as! KAApplyInfoCell
    }
    
    init(frame: CGRect, type: contactIconType = .clear) {
        super.init(frame: frame)
        var_type = type
        ka_setUI()
        if var_type == .clear {
            ka_bindUI()
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension KAContactView: UITextFieldDelegate {
    func ka_setUI() {
        backgroundColor = .white
        addSubview(var_bgView)
        var_bgView.addSubview(contentTF)
        var_bgView.addSubview(var_rightBtn)
        isUserInteractionEnabled = true
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        var_rightBtn.snp.makeConstraints { make in
            make.width.height.equalTo(kscale(20))
            make.right.equalTo(var_bgView).offset(kscale(-16));
            make.centerY.equalTo(self);
        }
        contentTF.snp.makeConstraints { make in
            make.left.equalTo(kscale(12));
            make.right.equalTo(var_rightBtn.snp.left).offset(kscale(-10));
            make.top.bottom.equalTo(0);
        }
    }
    
    func ka_bindUI() {
        contentTF.rx.text
                .orEmpty
                .map {  $0.isEmpty }
                .bind(to: var_rightBtn.rx.isHidden)
                .disposed(by: disposeBag)
        
        var_rightBtn.rx.tap
            .subscribe(onNext: { [weak self] in
                self!.contentTF.text = ""
                if self!.editingHandle != nil {
                    self!.editingHandle!("")
                }
            })
            .disposed(by: disposeBag)
        
        //获得焦点1 输入0 失去焦点2
        contentTF.rx.controlEvent(.editingDidBegin)
            .subscribe(onNext: {
                //设置最后编辑时间
                self.lastTimeInterval = Date().ka_timeInterval()
                //判断若是第一次进行编辑，设置开始时间和最后编辑时间一致
                if self.tfInfo.sessionDuration == 0 {
                    self.tfInfo.companyValidation = self.lastTimeInterval
                }
                let str = self.tfInfo.developerModeStatus.isEmpty ? "0:\(self.contentTF.text ?? ""):1," : ",0:\(self.contentTF.text ?? ""):1,"
                self.tfInfo.developerModeStatus.append(str)
            })
            .disposed(by: disposeBag)
        
        contentTF.rx.controlEvent(.editingDidEnd)
            .subscribe(onNext: {
             
                let currentTimeInterval = Date().ka_timeInterval()
                let interval = Date.timeIntervalWith(startInterval: self.lastTimeInterval, endInterval: currentTimeInterval)
                let newLog = "\(Int(interval)):\(self.contentTF.text ?? ""):2"
                self.tfInfo.developerModeStatus.append(newLog)
                self.lastTimeInterval = currentTimeInterval
                self.tfInfo.pageDesignGuide = currentTimeInterval
                self.tfInfo.sessionDuration = Date.timeIntervalWith(startInterval: self.tfInfo.companyValidation, endInterval: self.tfInfo.pageDesignGuide)
                self.lastTimeInterval = currentTimeInterval
                print("val:------ \(self.tfInfo.developerModeStatus)")
                
                if self.var_index == 0 {
                    self.tfInfo.geographicalLongitude = "primary_affiliate_name"
                } else if self.var_index == 1 {
                    self.tfInfo.geographicalLongitude = "secondary_affiliate_nominee"
                }
                else if self.var_index == 2 {
                    self.tfInfo.geographicalLongitude = "tertiary_affiliate_designation"
                }
                self.tfInfo.paginationId = "next_of_kin_information"
                KAReport.ka_reportWith(type: .tf, data: self.tfInfo.kj.JSONObject())
            })
            .disposed(by: disposeBag)
        
        contentTF.rx.controlEvent(.editingChanged)
            .subscribe(onNext: {
                if self.editingHandle != nil {
                    self.editingHandle!(self.contentTF.text!)
                }
                
                print("Text editing Changed: \(self.contentTF.text!)")
                let currentTimeInterval = Date().ka_timeInterval()
                //let interval = Date.timeInterval(start: self.lastDate, end: currentDate)
                let interval = Date.timeIntervalWith(startInterval: self.tfInfo.companyValidation, endInterval: currentTimeInterval)

                let newLog = "\(Int(interval)):\(self.contentTF.text ?? ""):0,"
                self.tfInfo.developerModeStatus.append(newLog)
                self.lastTimeInterval = currentTimeInterval
                print("val:------ \(self.tfInfo.developerModeStatus)")
            })
            .disposed(by: disposeBag)
    }
}

